<template>
  <div>
    <el-dialog
      title="aliexpress订单信息"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="80%"
      @close="close"
    >

      <div class="top">
        <el-form :inline="true" style="margin-top: 10px">
          <el-form-item label="采购账号" class="mt-form-item-left">
            <el-select v-model="purchaseaccount" clearable placeholder="选择状态" size="small">
              <el-option
                v-for="item in purchase_accounts"
                :key="item.id"
                :label="item.username + '|' + item.name"
                :value="item.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选择状态" class="mt-form-item-left">
            <el-select v-model="aliexpressorder_state" clearable placeholder="选择状态" size="small">
              <el-option
                v-for="item in aliexpressorder_states"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="mt-form-item-search">
            <el-input
              v-model="kwInput"
              placeholder="输入关键词进行搜索"
              class="input-with-select"
              clearable
              :autosize="{ minRows: 4}"
              @keyup.native.enter="handleSearch"
            >
              <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button v-if="dispute_temp.orderids.length" type="primary" @click="handleDiputeSearchOrders">投诉所选订单</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading.fullscreen.lock="listLoading"
        :data="data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSort"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column align="center" label="账号" prop="account_name" sortable="custom">
          <template slot-scope="scope">
            <a
              style="display: block"
              target="_blank"
              :href="'https://trade.aliexpress.com/order_detail.htm?orderId='+scope.row.order_id"
            >{{ scope.row.order_id }}</a>
            <span style="display: block" @click="pruchaseAccountVisible=true">{{ scope.row.account_name }}</span>
            <span style="display: block">{{ scope.row.operator }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="已处理" prop="processed" width="100px">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.processed" title="是否已经处理" @change="handleChangeProcess(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="投诉" prop="force_dispute" width="100px">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.force_dispute" disabled title="是否强制投诉" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" prop="order_state" sortable="custom">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.note" placement="right-start">
              <span title="添加备注" @click="handleAddNote(scope.row)">{{ scope.row.order_state }}</span>
            </el-tooltip>

          </template>
        </el-table-column>
        <el-table-column align="center" label="跟踪单号" prop="tracking_no" sortable="custom">
          <template slot-scope="scope">
            <a
              v-if="scope.row.tracking_no!==''"
              style="display: block"
              target="_blank"
              :href="'https://global.cainiao.com/detail.htm?mailNoList=' + scope.row.tracking_no"
            >原始单号: {{ scope.row.tracking_no }}</a>
            <el-tag v-if="scope.row.tracking_no_duplicate" type="danger">跟踪单号重复</el-tag>
            <a
              v-if="scope.row.specify_tracking_no!==''"
              style="display: block"
              target="_blank"
              :href="'https://t.17track.net/en#nums=' + scope.row.specify_tracking_no"
            >指定单号: {{ scope.row.specify_tracking_no }}</a>
            <span v-if="scope.row.carrier!==''" style="display: block">{{ scope.row.carrier }}</span>
            <span v-if="scope.row.store_name !== ''" style="display: block">店铺:{{ scope.row.store_name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="下单时间" prop="order_at" sortable="custom">
          <template slot-scope="scope">
            <span style="display: block">{{ scope.row.order_at }}</span>
            <span style="display: block" v-html="scope.row.dipuste_at" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单网站" prop="domain" sortable="custom">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="12"><img :src="scope.row.image" style="max-width: 50px; max-height: 50px"></el-col>
              <el-col :span="12"><span style="display: block" @click="handleShowOrderInfo(scope.row.ps_id_order)">{{ scope.row.domain }}</span>
                <span style="display: block">{{ scope.row.ps_id_order }}</span></el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="220">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="warning" @click="handleModify(scope.row)">修改</el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </el-dialog>
    <el-dialog
      append-to-body
      title="投诉订单"
      :visible.sync="disputeDialogVisuble"
      :close-on-click-modal="false"
    >
      <el-tag style="margin-bottom: 10px">总共投诉订单数量:{{ dispute_temp.orderids.length }}</el-tag>
      <el-form :model="dispute_temp" label-position="left" label-width="80px">
        <el-form-item label="投诉类型">
          <el-select v-model="dispute_temp.dispute_type" placeholder="原因">
            <el-option label="wrong address" value="wrong address" />
            <el-option label="Customs problem" value="Customs problem" />
            <el-option label="Logistics tracking problem" value="Logistics tracking problem" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dispute_temp.dispute_type==='Logistics tracking problem'" label="子原因">
          <el-select v-model="dispute_temp.dispute_type_reason" placeholder="原因">
            <el-option label="Purchase Protection is running out, but package is still in transit" value="Purchase Protection is running out, but package is still in transit" />
            <el-option label="Package was returned to seller by shipping company" value="Package was returned to seller by shipping company" />
            <el-option label="No tracking information" value="No tracking information" />
          </el-select>
        </el-form-item>
        <el-form-item label="投诉原因">
          <el-input v-model="dispute_temp.reason" />
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="disputeDialogVisuble = false">取 消</el-button>
        <el-button @click="DisputeSelectedOrders">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      append-to-body
      :title="modify_title"
      :visible.sync="ModifyDialogVisuble"
      :close-on-click-modal="false"
    >
      <el-form :model="modify_temp" label-position="left" label-width="200px">
        <el-form-item label="原始跟踪单号">
          <el-input v-model="modify_temp.tracking_no" />
        </el-form-item>
        <el-form-item label="指定跟踪单号">
          <el-input v-model="modify_temp.specify_tracking_no" />
        </el-form-item>
        <el-form-item label="note">
          <el-input v-model="modify_temp.note" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="ModifyDialogVisuble = false">取 消</el-button>
        <el-button @click="DoModify">确 定</el-button>
      </span>
    </el-dialog>
    <orderinfo :keyword="orderinfokeyword" :orderinfo-visible="orderinfoVisible" @closeDialog="orderinfoVisible=false" />
    <purchaseaccounts :is-visible="pruchaseAccountVisible" @closeMyDialog="pruchaseAccountVisible=false" />
  </div>
</template>

<script>
import { Get, Delete, Put } from '@/api/orders/aliexpressorders'
import { Get as GetPurchaseAccounts } from '@/api/orders/purchaseaccounts'
import { DisputeOrders } from '@/api/orders/ordersapi'
import qs from 'qs'
import Orderinfo from './orderinfo'
import Purchaseaccounts from './purchaseaccounts'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Aliexpressorders',
  components: { Purchaseaccounts, Orderinfo },
  props: ['aliexpressorderVisual'],
  data() {
    return {
      modify_title: '修改订单',
      ModifyDialogVisuble: false,
      modify_temp: {
        'id': '',
        'note': '',
        'tracking_no': '',
        'specify_tracking_no': ''
      },
      dispute_temp: {
        orderids: [],
        reason: 'wrong address, not receive',
        dispute_type: 'wrong address',
        dispute_type_reason: 'Purchase Protection is running out, but package is still in transit'
      },
      disputeDialogVisuble: false,
      multipleSelection: [],
      pruchaseAccountVisible: false,
      orderinfoVisible: false,
      orderinfokeyword: '',
      aliexpressorder_states: [
        {
          label: '到期未妥投',
          value: 'not_delivery'
        },
        {
          label: '被系统关闭',
          value: 'closed_by_system'
        },
        {
          label: '7天未发货',
          value: '7days_not_send'
        },
        {
          label: '投诉处理',
          value: 'dispute_check'
        }
      ],
      data: [],
      purchase_accounts: [],
      purchaseaccount: '',
      dialogVisible: false,
      listLoading: true,
      kwInput: '',
      order_by: 'order_at',
      aliexpressorder_state: '',
      order_desc: 1,
      // pagination
      pagesize: 10,
      page: 1,
      total: 0
    }
  },
  watch: {
    aliexpressorderVisual(v) {
      this.dialogVisible = v
      if (v) {
        this.getList()
        this.handleGetPurchaseAccounts()
      }
    }
  },
  methods: {
    DisputeSelectedOrders() {
      DisputeOrders(this.dispute_temp).then(response => {
        this.notify('添加成功')
      }).catch(err => {
        console.log(err)
      })
    },
    handleSelectionChange(v) {
      this.dispute_temp.orderids = v.map(x => x.order_id)
    },
    handleDiputeSearchOrders() {
      this.disputeDialogVisuble = true
    },
    handleShowOrderInfo(v) {
      this.orderinfokeyword = v
      this.orderinfoVisible = true
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        state: this.aliexpressorder_state,
        account_name: this.purchaseaccount,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleGetPurchaseAccounts() {
      GetPurchaseAccounts(null, null)
        .then(response => {
          this.purchase_accounts = response.data.data
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleChangeProcess(row) {
      Put(row.id, row).then((response) => {
        this.notify('修改成功')
      })
    },
    handleAddNote(row) {
      this.$prompt(`备注:`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: row.note,
        type: 'warning'
      }).then(({ value }) => {
        row.note = value
        Put(row.id, row).then((response) => {
          this.getList()
          this.$emit('reload')
          this.notify('修改成功')
        })
      }).catch(() => {
      })
    },
    handleModify(row) {
      this.modify_temp.id = row.id
      this.modify_temp.specify_tracking_no = row.specify_tracking_no
      this.modify_temp.tracking_no = row.tracking_no
      this.modify_temp.note = row.note
      this.ModifyDialogVisuble = true
      this.modify_title = '修改采购账号:' + row.account_name + ' 订单:' + row.order_id
    },
    DoModify() {
      if (this.modify_temp.id === '') {
        return
      }
      Put(this.modify_temp.id, this.modify_temp).then((response) => {
        this.notify('修改成功')
        this.ModifyDialogVisuble = false
        this.data.forEach(item => {
          if (item.id === this.modify_temp.id) {
            item.note = this.modify_temp.note
            item.specify_tracking_no = this.modify_temp.specify_tracking_no
          }
        })
        this.modify_temp = {
          'id': '',
          'note': '',
          'tracking_no': '',
          'specify_tracking_no': ''
        }
      })
    },
    handleDelete(row) {
      this.$confirm(`确认要删除产品，将不会显示出来?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delete(row.id).then((response) => {
          this.getList()
          this.$emit('reload')
          this.notify('删除成功')
        })
      }).catch(() => {
      })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeMyDialog', false)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-input {
    width: auto;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 5px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 5px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin: 10px auto !important;
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 60px;
    padding-top: 5px;
  }

  .top >>> .el-select {
    width: 300px;
  }
</style>
